<template>
    <view class="all">
        <!-- <view class="colseshow" @click="CloseWindow"></view> -->
        <view class="head">
            <text>编辑物品</text>
            <image @click="CloseWindow" src="../../static/img/myhome/close@3x.png" mode=""></image>
        </view>
        <view class="backgroundcolor">
            <scroll-view scroll-y="true">
                <view class="box">
                    <view class="selecttype" @click="show = true">
                        <text>物品类型</text>
                        <view>
                            <text style="overflow: hidden;white-space: nowrap; text-overflow: ellipsis;">{{ selectText || '请选择' }}</text>
                            <u-icon name="arrow-down-fill" color="#999999" size="20"></u-icon>
                        </view>
                    </view>
                    
                    <view class="oneprice">
                        <text>单价</text>
                        <input type="digit" v-model="wp.unit_price" :disabled="priceDisabled" />
                        <view>
                            <text>元/{{ jlList[wp.unit] }}</text>
                        </view>
                    </view>
                    
                    <view class="selecttype" style="margin-top: 20rpx;" v-if="(jlList[wp.unit] == 'KG') && (isGetWeight == 1)">
                        <text>地磅仪表</text>
                        <view>
                            <text>{{ table_show }}</text>
                        </view>
                    </view>

                    <!-- 过磅 -->
                    <view class="selectgb" v-if="jlList[wp.unit] == 'KG'">
                        <view class="type"><text>点击获取过磅</text></view>
                        <view class="kg">
                            <view class="label-text" @click="beforeCount()"><text>卸车前过磅</text></view>
                            <view><input type="digit" @change="aWeight" placeholder="卸车前过磅" v-model="wp.b_weigh" /></view>
                            <view>
                                <text>{{ jlList[wp.unit] }}</text>
                            </view>
                        </view>
                        <view class="kg">
                            <view class="label-text" @click="afterCount()"><text>卸车后过磅</text></view>
                            <view><input type="digit" @change="aWeight" placeholder="卸车后过磅" v-model="wp.a_weigh" /></view>
                            <view>
                                <text>{{ jlList[wp.unit] }}</text>
                            </view>
                        </view>
                    </view>
                    
                    <view class="oneprice" v-if="jlList[wp.unit] == 'KG'">
                        <text>回皮重量</text>
                        <input type="digit" placeholder="0" v-model="wp.r_weigh" />
                        <view>
                            <text>KG</text>
                        </view>
                    </view>

                    <view class="selectkg">
                        <view class="type">
                            <text>计量方式</text>
                            <view>
                                <picker @change="jlType" :range="jlList" disabled>
                                    <label class="select">{{ jlList[wp.unit] }}</label>
                                    <!-- <i></i> -->
                                </picker>
                            </view>
                        </view>
                        <view class="kg">
                            <view><input type="digit" placeholder="请输入数量/重量" v-model="wp.nums" /></view>
                            <view>
                                <text>{{ jlList[wp.unit] }}</text>
                            </view>
                        </view>
                    </view>

                    <view class="img">
                        <view class="type"><text>上传图片</text></view>
                        <view class="kg">
                            <u-upload
                                ref="upload"
                                :action="baseUrl + '/api/images/upload'"
                                :file-list="imgurls"
                                :form-data="{ code: '999' }"
                                width="150rpx"
                                height="150rpx"
                                @on-success="uploadSu"
                                @on-remove="oploadRe"
                            ></u-upload>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
        <view class="button">
            <button @click="postedit"><span>确定</span></button>
        </view>

        <u-select
            mode="mutil-column-auto"
            v-model="show"
            :list="wptypelist"
            value-name="id"
            :default-value="defaultValue"
            label-name="wp_name"
            child-name="plist"
            @confirm="confirm"
        ></u-select>
    </view>
</template>

<script>
import { v4 } from 'uuid';
var mqtt = require('mqtt/dist/mqtt.js');
//import { MQTT_IP, MQTT_PORT, MQTT_OPTIONS } from '@/untlis/mqtt_config.js';
export default {
    data() {
        return {
            // 物品的类型
            wptypelist: [],
            // 计量的方式
            jlList: ['KG', '个/台'],
            selectText: '',
            show: false,
            baseUrl: '',
            wp: {},
            imgurls: [],
            index: 0,
            defaultValue: [],
            priceDisabled: true,
            //20220909
            isGetWeight: 0,
            table_show: 0,
            clientConn: null
        };
    },
    created() {
        //var that = this;
        //that._getTweight();
        //20220908 created比cre快
    },
    methods: {
        aWeight(v) {
            let bWeigh = this.wp.b_weigh ? parseFloat(this.wp.b_weigh) : 0;
            let aWeigh = this.wp.a_weigh ? parseFloat(this.wp.a_weigh) : 0;
            this.wp.nums = this.count(bWeigh, aWeigh);
        },
        count(a, b) {
            var multiple = 1000;
            return Math.round(parseFloat(a) * multiple - parseFloat(b) * multiple) / multiple;
        },
        handPriceDisabled() {
            this.priceDisabled = false;
        },
        cre(item, index, isGetWeight) {
            //console.log("-----------cre----------");
            this.wp = item;
            this.index = index;
            this.baseUrl = this.$store.state.baseUrl;
            this.wptypelist = this.$store.state.wptypelist;
            this.selectText = item.wp_name;
            this.wp.weight == '个' ? (this.wp.weight = '个') : (this.wp.weight = 'KG');
            let imgurls = [];
            this.wp.img.forEach((item, index) => {
                if (!this.$u.test.isEmpty(item)) {
                    imgurls.push({ url: item });
                }
            });
            this.imgurls = imgurls;
            this.defaultValue = [];
            this.wptypelist.forEach((item, index) => {
                if (item.plist.length > 0) {
                    item.plist.forEach((im, idex) => {
                        if (im.plist) {
                            im.plist.forEach((i, idx) => {
                                if (i.id == this.wp.wp_type[2]) {
                                    this.defaultValue.unshift(idx);
                                    return;
                                }
                            });
                        }
                        if (im.id == this.wp.wp_type[1]) {
                            this.defaultValue.unshift(idex);
                            return;
                        }
                    });
                }
                if (item.id == this.wp.wp_type[0]) {
                    this.defaultValue.unshift(index);
                    return;
                }
            });
            
            //20220908获取重量
            // this.isGetWeight = isGetWeight;
            // if (isGetWeight && isGetWeight == 1) this._getTweight();
        },
        oploadRe(index) {
            this.wp.img.splice(index, 1);
        },
        uploadSu(data) {
            this.wp.img.push(data.data.url);
        },
        // 关闭添加物品弹窗
        CloseWindow() {
            //20221107关闭mqtt连接
            this.clientConn.end();
            this.$emit('closewin');
        },
        // 选择计量方式
        jlType(e) {
            this.wp.unit = e.target.value;
            this.wp.weight = this.jlList[this.wp.unit];
        },
        // 确定编辑
        postedit() {
            //20221107关闭mqtt连接
            // this.clientConn.end();
            this.wp.imgs = this.wp.img.join(',');
            //计算总价按重量，按数量
            if (this.wp.unit == 0) {
                let rWeigh = this.wp.r_weigh ? parseFloat(this.wp.r_weigh) : 0;
                let bWeigh = this.wp.b_weigh ? parseFloat(this.wp.b_weigh) : 0;
                let aWeigh = this.wp.a_weigh ? parseFloat(this.wp.a_weigh) : 0;
                
                this.wp.total_price = (bWeigh - aWeigh - rWeigh) * parseFloat(this.wp.unit_price);
            } else if (this.wp.unit == 1) {
                this.wp.total_price = this.wp.nums * this.wp.unit_price;
            }
            
            if (this.$u.test.isEmpty(this.wp.weight)) {
                this.wp.weight = 'KG';
            }
            if (parseFloat(this.wp.unit_price) == 0) {
                uni.showToast({
                    title: '请输入价格!',
                    duration: 1000,
                    icon: 'none'
                });
                return false;
            }
            if (this.$u.test.isEmpty(this.wp.wp_name)) {
                uni.showToast({
                    title: '请选择物品',
                    duration: 1000,
                    icon: 'none'
                });
                return false;
            } 
            if (this.$u.test.isEmpty(this.wp.nums)) {
                uni.showToast({
                    title: '请选择输入数量或重量',
                    duration: 1000,
                    icon: 'none'
                });
                return false;
            } 
            if (!this.$u.test.amount(this.wp.unit_price)) {
                uni.showToast({
                    title: '请输入正确金额',
                    duration: 1000,
                    icon: 'none'
                });
                return false;
            }
            // else if (this.$u.test.isEmpty(this.wp.imgs)) {
            //     uni.showToast({
            //         title: '请上传图片',
            //         duration: 1000,
            //         icon: 'none'
            //     });
            //     return ;
            // }
            //else {
            //    this.$emit('myEven', {wp: this.wp, index: this.index});
            //}
            this.$emit('myEven', {wp: this.wp, index: this.index});
        },
        confirm(e) {
            this.selectText = e[1].label;
            this.wp.wp_name = e[1].label;
            // this.wp.wsize = e[2].label;
            this.wp.unit_price = e[1].extra.split(',')[0];
            this.wp.unit = Number(e[1].extra.split(',')[1]);
            this.wp.weight = this.wp.unit == 0 ? 'KG' : '个';
            this.wp.wp_type = [e[0].value, e[1].value];
        },
        //20220908
        //确定过磅前重量
        beforeCount(){
            var that = this;
            that.wp.nums = that.table_show;
            if (that.isGetWeight == 1) that.wp.b_weigh = that.table_show;
        },
        //确定过磅后重量
        afterCount(){
            var that = this;
            that.wp.nums = that.table_show;
            if (that.isGetWeight == 1) that.wp.a_weigh = that.table_show;
        },
        //获取货物重量
        // _getTweight() {
        //     var that = this;
        //     that.isGetWeight = 1;
        //     let options = {
        //         connectTimeout: 5000,
        //         clientId: "",
        //         username: "",
        //         password: "",
        //         clean: false
        //     };
        //     options.clientId = v4();
        //     //2023/3/22
        //     let service_init = uni.getStorageSync('service_init')
        //     let service_setting = service_init.service_setting
        //     if (!service_setting) {
        //         uni.showToast({
        //             title: '地磅连接错误，请联系管理员5',
        //             icon:'none'
                    
        //         })
        //         return
        //     }
        //     // options.username = that.$store.state.MQTT_USERNAME;
        //     // options.password = that.$store.state.MQTT_PASSWORD;
        //     // let MQTT_PORT = that.$store.state.MQTT_PORT;
        //     options.username = service_setting.MQTT_USERNAME;
        //     options.password = service_setting.MQTT_PASSWORD;
        //     let MQTT_PORT = service_setting.MQTT_PORT;
        //     let MQTT_TOPIC = "";
        //     // let MQTT_NUMBER = that.$store.state.MQTT_NUMBER;
        //     let MQTT_NUMBER = service_setting.MQTT_NUMBER;
        //     MQTT_TOPIC = "/CloudComData/"+ MQTT_NUMBER;
        //     // let connUrl = "wxs://" + that.$store.state.MQTT_IP + ":" + MQTT_PORT + "/mqtt"; //线上
        //     let connUrl = "wxs://" + service_setting.MQTT_IP + ":" + MQTT_PORT + "/mqtt"; //线上
        //     console.log("MQTT_TOPIC:" + MQTT_TOPIC);
        //     console.log("MQTT_NUMBER:" + MQTT_NUMBER);
        //     console.log(connUrl);
        //     that.clientConn = mqtt.connect(connUrl, options);
        //     that.clientConn.on("connect", function() {
        //         console.log("连接成功......");
        //         that.clientConn.subscribe(MQTT_TOPIC, function(err) {
        //             if (!err) console.log("订阅成功......");
        //         });
        //     }).on("reconnect", function(error) {
        //         console.log("正在重新连接......", error);
        //     }).on("error", function(error) {
        //         console.log("连接失败......", error);
        //     }).on("end", function() {
        //         console.log("连接断开......");
        //     }).on("message", function(topic, message) {
        //         let encodedString = String.fromCharCode.apply(null, new Uint8Array(message));
        //         let finalWeight = parseFloat(encodedString) * 1000;
        //         console.error(finalWeight, '地磅数')
        //         if (finalWeight > 0) {
        //             that.table_show = finalWeight;
        //         }
        //         console.log(message);
        //         console.log(encodedString);
        //     });
        //     /*this.$u.api.postTableWeight(param).then(res => {
        //         that.table_show = res.weight;
        //         //that.wp.nums = res.weight;
        //         //console.log(res);
        //     });*/
        //     //var clientId = v4();
        //     //console.log("--------clientId show-----------");
        //     //console.log(clientId);
        // }
    }
};
</script>

<style lang="scss" scoped>
.all {
    position: relative;
    height: 100%;
}

.head {
    height: 88rpx;
    background-color: #ffffff;

    text {
        margin-left: 30rpx;
        line-height: 88rpx;
    }

    image {
        float: right;
        width: 85rpx;
        height: 85rpx;
    }
}

.box {
    padding: 30rpx;
    max-height: 800rpx;

    picker {
        width: 440rpx;
        height: 60rpx;
        background-color: #f7f7f7;
        border-radius: 10rpx;
        border: solid 2rpx #f2f2f2;
        padding: 0 28rpx;
        color: #999999;
        font-size: 28rpx;
        line-height: 60rpx;

        i {
            margin-top: 30rpx;
            float: right;
            width: 0;
            height: 0;
            border: 10rpx solid;
            border-color: #999999 transparent transparent;
        }
    }
}

.selecttype {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 98rpx;
    background-color: #ffffff;
    border-radius: 20rpx;

    view {
        width: 440rpx;
        height: 60rpx;
        background-color: #f7f7f7;
        border-radius: 10rpx;
        border: solid 2rpx #f2f2f2;
        padding: 0 28rpx;
        color: #999999;
        font-size: 28rpx;
        line-height: 60rpx;
        display: flex;
        justify-content: space-between;
    }
}
.selectgb {
    margin-top: 30rpx;
    // display: flex;
    // justify-content: space-around;
    // align-items: center;
    padding: 18rpx 0 25rpx 0;
    background-color: #ffffff;
    border-radius: 20rpx;

    view {
        display: flex;
        justify-content: space-around;
        align-items: center;
    }

    .type {
        border-bottom: 1px solid #eeeeee;
        padding-bottom: 15rpx;
        justify-content: flex-start;
        padding-left: 15rpx;
    }

    .kg {
        margin: 30rpx 30rpx 0;
        width: 630rpx;
        border-radius: 10rpx;
        border: solid 2rpx #e5e5e5;
        background-color: #ffffff;
        display: flex;
        justify-content: space-between;

        view:nth-child(1) {
            width: 165rpx;
            height: 70rpx;
            border-right: solid 2rpx #e8e9ed;
            background-color: #f7f7f7;
        }
        view:nth-child(2) {
            flex-grow: 1;
            background-color: #ffffff;

            text {
                font-size: 24rpx;
                color: #666666;
            }

            input {
                font-size: 24rpx;
                color: #666666;
            }
        }

        view:nth-child(3) {
            width: 125rpx;
            height: 70rpx;
            border-left: solid 2rpx #e8e9ed;
            background-color: #f7f7f7;

            text {
                font-size: 24rpx;
                color: #191919;
            }
        }
    }
}

.selectkg {
    margin-top: 30rpx;
    // display: flex;
    // justify-content: space-around;
    // align-items: center;
    padding: 18rpx 0 25rpx 0;
    background-color: #ffffff;
    border-radius: 20rpx;

    view {
        display: flex;
        justify-content: space-around;
        align-items: center;
    }

    .type {
        border-bottom: 1px solid #eeeeee;
        padding-bottom: 15rpx;
    }

    .kg {
        margin: 30rpx 30rpx 0;
        width: 630rpx;
        border-radius: 10rpx;
        border: solid 2rpx #e5e5e5;
        background-color: #ffffff;

        view:nth-child(1) {
            width: 630rpx;
            background-color: #ffffff;

            text {
                font-size: 24rpx;
                color: #666666;
            }
        }

        view:nth-child(2) {
            width: 125rpx;
            height: 70rpx;
            border-left: solid 2rpx #e8e9ed;
            background-color: #f7f7f7;

            text {
                font-size: 24rpx;
                color: #191919;
            }
        }
    }
}

.oneprice {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 30rpx;
    height: 98rpx;
    // line-height: 98rpx;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 0 30rpx;
}

.img {
    margin-top: 30rpx;
    // height: 273rpx;
    // display: flex;
    // justify-content: space-around;
    // align-items: center;
    padding: 18rpx 29rpx 25rpx 29rpx;
    background-color: #ffffff;
    border-radius: 20rpx;

    .type {
        height: 98rpx;
        line-height: 98rpx;
        border-bottom: 1px solid #eeeeee;
        padding-bottom: 15rpx;

        text {
            margin-right: 505rpx;
        }
    }

    .kg {
        margin-top: 30rpx;
        width: 630rpx;
        border-radius: 10rpx;
        background-color: #ffffff;
        // margin-bottom: 210rpx;

        image {
            width: 120rpx;
            height: 120rpx;
            margin-right: 20rpx;
            background-color: #f2f2f2;
            border-radius: 10rpx;
        }
    }
}

.button {
    position: flexd;
    left: 10rpx;
    padding: 20rpx 0;
    height: 140rpx;
    background-color: #eeeeee;

    button {
        width: 570rpx;
        height: 98rpx;
        background-color: #1bc078;
        border-radius: 49rpx;
    }

    span {
        font-size: 28rpx;
        color: #ffffff;
    }
}

.colseshow {
    width: 750rpx;
    height: calc(100% - 1028rpx);
    opacity: 0.1;
    background-color: #000000;
}

.backgroundcolor {
    background-color: #eeeeee;
}
.label-text {background-color: #f0ad4e !important;}
</style>
